package com.rent.common.exception;

import com.rent.common.entity.ResponseResult;
import com.rent.common.enums.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 * 统一处理系统中的各种异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseResult<Void> handleBusinessException(BusinessException e) {
        log.error("业务异常：{}", e.getMessage());
        return ResponseResult.fail(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理参数校验异常（@Valid）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<Void> handleValidationException(MethodArgumentNotValidException e) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        StringBuilder sb = new StringBuilder("参数校验失败：");
        for (ObjectError error : errors) {
            sb.append(error.getDefaultMessage()).append("; ");
        }
        log.error("参数校验异常：{}", sb);
        return ResponseResult.fail(ResponseCode.BAD_REQUEST.getCode(), sb.toString());
    }
    
    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseResult<Void> handleBindException(BindException e) {
        List<ObjectError> errors = e.getAllErrors();
        StringBuilder sb = new StringBuilder("参数绑定失败：");
        for (ObjectError error : errors) {
            sb.append(error.getDefaultMessage()).append("; ");
        }
        log.error("参数绑定异常：{}", sb);
        return ResponseResult.fail(ResponseCode.BAD_REQUEST.getCode(), sb.toString());
    }
    
    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public ResponseResult<Void> handleNullPointerException(NullPointerException e) {
        log.error("空指针异常：", e);
        return ResponseResult.error("系统内部错误");
    }
    
    /**
     * 处理其他未知异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult<Void> handleException(Exception e) {
        log.error("系统异常：", e);
        return ResponseResult.error("系统内部错误，请联系管理员");
    }
}

